<template>
	<div>
		<van-popup round v-model:show="show" position="bottom" :close-on-click-overlay="true">
			<div class="popup-box">
				<ul>
					<li class="item" v-for="item in operationList" :key="item.value" @click="handleOperationSelect(item)">
						{{ item.text }}
					</li>
				</ul>
			</div>
		</van-popup>

		<van-dialog v-model:show="dialogState.show" :title="dialogState.title" show-cancel-button
			:beforeClose="handleBeforeClose">
			<van-field v-model="dialogState.agentUserName" label-width="0" :placeholder="`请输入${level}级代理用户名`" />
		</van-dialog>

		<van-popup v-model:show="popupState.show" class="w-full" style="height: 100%" position="right">
			<div class="page">
				<global-header title="添加下线" @back="popupState.show = false" />
				<van-field v-model="popupState.name" label-width="0" placeholder="请输入下线用户名" />

				<van-field v-model="popupState.value" label="批量修改" type="digit" @change="handleMaster">
					<template #right-icon>
						%
					</template>
				</van-field>


				<div class="bg-white mt-[10px] list-header ">
					<div class="row-start-center text-[14px] text-[#888] py-[12px] px-[15px]"
						style="border-bottom: 1px solid #e4e4e4">
						<div class="flex-1 text-left">游戏名称</div>
						<div class="w-[25%] text-center">返佣比例</div>
					</div>
				</div>
				<main class="page-main bg-white">
					<div v-for="(item, i) in games" :key="i" class="row-start-center text-[14px] text-[#888] py-[12px] px-[15px]"
						style="border-bottom: 1px solid #e4e4e4">
						<div class="flex-1 text-left">{{ item.Name }}</div>
						<div class="w-[25%] text-center !bg-[#F1F4FB] truncate">
							<van-field v-model="item.BackRate" class="!px-[6px] !py-[4px]" input-align="center" label-width="0"
								type="digit">
								<template #right-icon>
									%
								</template>
							</van-field>
						</div>
					</div>
				</main>
				<div class="p-[15px] bg-[#FFFFFF]">
					<div class="flex gap-[10px]">
						<van-button @click="popupState.show = false;" class="!flex-1 !bg-[#CDD9EE] !text-[#3976CC] rounded-[5px]"
							block>
							取消
						</van-button>
						<van-button @click="confirm()" class="!flex-1 !bg-[#3976CC] !text-[#FFFFFF]  rounded-[5px]" block>
							保存设置
						</van-button>
					</div>
				</div>
			</div>
		</van-popup>
	</div>
</template>
<script setup lang="ts">
import { toast } from '@/utils/toast';
import { reactive } from 'vue';

import { reqAddAgentUser, reqDelAgent, reqUserBecomeAgent } from "@/api/user";
import { useGameStore } from '@/store/modules/game';
import { storeToRefs } from 'pinia';
import { debounce } from 'lodash-es';
import { toChinesNum } from "@/utils/common";

const emit = defineEmits<{
	update: []
}>()

const dialogState = reactive({
	show: false,
	title: '',
	agentUserName: ''
})

const level = computed(() => {
	return toChinesNum(((props.info!.Level || 0) + 1))
})

const handleBeforeClose = async (action: "confirm" | "cancel") => {

	if (action == 'confirm') {
		if (dialogState.agentUserName.trim()) {
			const params = {
				Name: dialogState.agentUserName.trim(),
				ParentId: props.info!.UserId
			};
			try {
				await reqUserBecomeAgent(params);
				toast.success(`添加${level}级代理成功`)
				return true;
			} catch (error) {
				return false;
			}
		}
		toast.fail(`请输入${level}级代理用户名`)
		return false;
	} else {
		dialogState.agentUserName = "";
		dialogState.show = false;
	}

	return true;
};

const gameStore = useGameStore();
const { gameTotal } = storeToRefs(gameStore);
const games = ref(
	gameTotal.value.map(item => {
		return {
			...item,
			BackRate: 0
		};
	})
);

const popupState = reactive({
	show: false,
	name: "",
	value: 0
})
const handleMaster = (val: number) => {
	games.value.forEach(item => {
		item.BackRate = popupState.value;
	});
};


const props = withDefaults(
	defineProps<{
		info: AgentMo | null;
	}>(),
	{}
);
const show = ref(false);
const operationList = ref([
	{ text: "添加二级代理", value: "add-second" },
	{ text: "添加下线", value: "add-sub" },
	{ text: "取消代理", value: "cancel-agent" },
]);

watch(() => props.info, (value: any) => {
	operationList.value[0].text = `添加${toChinesNum(((props.info!.Level || 0) + 1))}级代理`
}, {
	deep: true
})

const confirm = debounce(
	async () => {
		if (!props.info) return;
		if (!popupState.name) {
			toast.fail("请输入下线用户名");
			return;
		}
		try {
			const commissionRate: Record<string, any> = {};
			for (let item in games.value) {
				commissionRate[String(games.value[item].LotteryId)] = games.value[item].BackRate;
			}
			const params = {
				UserName: popupState.name,
				ParentId: props.info.UserId,
				CommissionRate: JSON.stringify(commissionRate)
			};
			await reqAddAgentUser(params);
			popupState.name = "";
			toast.success(`添加下线成功`);
			popupState.show = false;
		} catch (error) {
			console.log(error);
		}
	},
	500,
	{ leading: true, trailing: false }
);




const handleOperationSelect = (item: { text: string; value: string }) => {
	show.value = false;
	switch (item.value) {
		case "add-second":
			dialogState.title = `添加${level.value}级代理`
			dialogState.agentUserName = "";
			dialogState.show = true;
			break;
		case "add-sub":
			popupState.show = true;
			break;
		case "cancel-agent":
			showConfirmDialog({
				title: "",
				message: "是否进行【取消代理操作】",
				beforeClose: async (action: string) => {
					return new Promise<boolean>(async resolve => {
						if (action === "confirm") {
							try {
								await reqDelAgent(props.info!.UserId);
								toast.success("取消代理成功");
								emit("update")
							} catch (error) {
							}
						}
						resolve(true);
					})
				}
			});
			break;
		default:
			break;
	}
};

defineExpose({
	open() {
		show.value = true;
	}
});
</script>
<style scoped lang="scss">
.popup-box {
	@apply py-[5px];
}

.popup-box .item {
	@apply h-[50px] text-[14px] text-center leading-[50px] border-solid border-b-[1px] border-[#E4E4E4];
}


.truncate {
	// border: 1px solid red;
	background: #F1F4FB;
	border-radius: 5px 5px 5px 5px;
	border: 1px solid #3976CC;
	display: flex;
	justify-content: center;
	align-items: center;
}
</style>
